package raccoon.plugin.mybatis;

import raccoon.plugin.mybatis.type.BatchList;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ConfigurationStealer;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.Transaction;

import java.lang.reflect.Proxy;
import java.util.Properties;

/**
 * Created by Administrator on 2016/6/30.
 */

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {
        MappedStatement.class, Object.class
    })
})
public class BatchSQLModeInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Object[] args = invocation.getArgs();

        MappedStatement mappedStatement = (MappedStatement) args[0];
        Class<?> type = mappedStatement.getParameterMap().getType();
        if(BatchList.class.isAssignableFrom(type)){
            Executor executor = newExecutor(mappedStatement.getConfiguration(),((Executor)invocation.getTarget()).getTransaction());
            return executor.update(mappedStatement,args[1]);
        }
        else return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {

        if(!Proxy.isProxyClass(target.getClass()) && !(target instanceof MyBatchExecutor) && Executor.class.isAssignableFrom(target.getClass())){
            return Plugin.wrap(target,this);
        }
        return target;
    }
    private Executor newExecutor(Configuration configuration,Transaction transaction) {
        Executor executor = new MyBatchExecutor(configuration,transaction);
        executor = (Executor) ConfigurationStealer.getInterceptorChain(configuration).pluginAll(executor);
        return executor;
    }
    @Override
    public void setProperties(Properties properties) {

    }
}
